package awesome.cpu.structure;

import awesome.cpu.utils.Mode;

public class MuxPC2M extends NonSequentialComponent {
	
	private static boolean outputDebug = false;
	
	public final static int KEY_IORD = 1;
	private int mIorD;
	
	public final static int KEY_PC = 2;
	private int mPC;
	public final static int KEY_ALUOUT = 3;
	private int mALUOut;
	
	public final static int KEY_SELECTED = 4;
	//private int mSelected;
	
	private final static MuxPC2M mInstance = new MuxPC2M();
	
	private MuxPC2M() {}
	
	public static MuxPC2M getInstance() {
		return mInstance;
	}

	@Override
	boolean setData(int keyInterface, int data) {
		switch (keyInterface) {
		case KEY_IORD:
			mIorD = data;
			return true;
		case KEY_PC:
			mPC = data;
			return true;
		case KEY_ALUOUT:
			mALUOut = data;
			return true;
		}
		return false;
	}

	@Override
	int getData(int keyInterface) {
		
		BusMonitor.transferData(Control.getInstance(), Control.KEY_I_OR_D,
				this, KEY_IORD);
		BusMonitor.transferData(PC.getInstance(), PC.KEY_PC_OUT,
				this, KEY_PC);
		BusMonitor.transferData(ALUOut.getInstance(), ALUOut.KEY_ALU_OUT_LO,
				this, KEY_ALUOUT);
		
		switch (keyInterface) {
		case KEY_SELECTED:
			return select();
		}
		return 0;
	}
	
	private int select() {
		switch (mIorD) {
		case 0:
			if (outputDebug && Mode.getDebugLevel() >= Mode.DEBUG_LEVEL_PRINT_ALL) {
				System.out.println("MuxPC2M: selected = "+mPC);
			}
			return mPC;
		case 1:
			if (outputDebug && Mode.getDebugLevel() >= Mode.DEBUG_LEVEL_PRINT_ALL) {
				System.out.println("MuxPC2M: selected = "+mALUOut + "+" + Memory.getInstance().getDataOffset());
			}
			return mALUOut + Memory.getInstance().getDataOffset();
		}		
		if (outputDebug && Mode.getDebugLevel() >= Mode.DEBUG_LEVEL_PRINT_ALL) {
			System.out.println("MuxPC2M: invalid IorD signal");
		}
		return 0;
	}
}
